<template>
  <div class="main">
    <div class="part">
      <!-- <div class="p-title">
        <div class="title">
          <span>订单查询</span>
        </div>
      </div> -->
      <div class="p-cont">
        <div class="title ep-bg-purple">
          <span>用药订单</span>
        </div>
        <div class="detail">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="d-label">姓名：</div>
              <div class="d-value">
                {{ orderData.patient.patientName }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">性别：</div>
              <div class="d-value">
                {{ orderData.patient.patientSex === 0 ? "女" : "男" }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">年龄：</div>
              <div class="d-value">
                {{ orderData.patient.patientAge }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">疾病诊断：</div>
              <div class="d-value">
                {{
                  orderData.diseases
                    .map(item => {
                      return item.name;
                    })
                    .join(",")
                }}
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="d-label">过敏史：</div>
              <div class="d-value">
                {{ orderData.patient.allergies }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">用药周期：</div>
              <div class="d-value">
                {{ orderData.cycle + "天" }}
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="p-cont">
        <div class="title ep-bg-purple">
          <span>药品信息</span>
        </div>
        <div class="detail">
          <el-table :data="orderData.drugs" style="width: 100%">
            <el-table-column
              prop="drugType"
              label="药品分类"
              :formatter="formatterDrugType"
              width="100"
            />
            <el-table-column prop="productCode" label="产品编码" width="100" />
            <el-table-column
              prop="productName"
              label="通用名(商品名称)"
              width="200"
            >
              <template #default="scope">
                {{
                  scope.row.productName
                    ? `${scope.row.commonName}(${scope.row.productName})`
                    : scope.row.commonName
                }}
              </template>
            </el-table-column>
            <el-table-column label="规格">
              <template #default="scope">
                {{
                  `${scope.row.preparationUnit}*${scope.row.packageSize}${scope.row.minimumUnit}/${scope.row.packageUnit}`
                }}
              </template>
            </el-table-column>
            <el-table-column label="单次用量">
              <template #default="scope">
                {{ `${scope.row.useAmount}${scope.row.minimumUnit}` }}
              </template>
            </el-table-column>
            <el-table-column
              prop="frequency"
              label="频次"
              :formatter="formatterFrequency"
            />
            <el-table-column label="单价￥">
              <template #default="scope">
                {{ formatMoney(scope.row.priceCent, 2).replace("¥", "") }}
              </template>
            </el-table-column>
            <el-table-column label="购买数量">
              <template #default="scope">
                {{ scope.row.amount + scope.row.packageUnit }}
              </template>
            </el-table-column>
            <el-table-column label="实售数量">
              <template #default="scope">
                {{
                  replaceRealNum(scope.row.realQuantity, scope.row.packageUnit)
                }}
              </template>
            </el-table-column>
          </el-table>
          <div class="table-footer">
            <el-row>
              <el-col :span="8"
                >合计金额：{{ formatMoney(moneyCent, 2) }}</el-col
              >
              <el-col :span="8">报销额：{{ refundCont }}</el-col>
              <el-col :span="8"
                >报销后金额：{{
                  formatMoney(moneyCent - whMoneyCent, 2)
                }}</el-col
              >
            </el-row>
            <el-row>
              <el-col :span="8"
                >实售金额：{{
                  replaceZero(realyMoneyCent, formatMoney(realyMoneyCent, 2))
                }}</el-col
              >
              <el-col :span="8"
                >报销现金额：{{
                  `${
                    orderData && orderData.refundMoney
                      ? "￥" + orderData.refundMoney
                      : "-"
                  }`
                }}</el-col
              >
              <el-col :span="8"
                >报销福利值：{{
                  isNaN(orderData.refundPoints)
                    ? "-"
                    : (Number(orderData.refundPoints) / 100).toFixed(2)
                }}</el-col
              >
            </el-row>
            <el-row>
              <el-col :span="8" />
              <el-col :span="8" />
              <el-col :span="8"
                >实报后金额：{{
                  replaceZero(
                    realyMoneyCent -
                      (orderData.refundMoney
                        ? Number(orderData.refundMoney) * 100
                        : 0),
                    formatMoney(
                      realyMoneyCent -
                        (orderData.refundMoney
                          ? Number(orderData.refundMoney) * 100
                          : 0),
                      2
                    )
                  )
                }}</el-col
              >
            </el-row>
          </div>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="p-cont">
        <div class="title ep-bg-purple">
          <span>订单流水</span>
        </div>
        <div class="detail">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in orderData.orderFlow.filter(item => {
                return !!item.content;
              })"
              :key="index"
              :timestamp="activity.createDate"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </div>

    <!-- <div class="part">
      <div class="p-cont">
        <div class="title ep-bg-purple">
          <span>应付信息</span>
        </div>
        <div class="detail" />
      </div>
    </div> -->

    <div class="part">
      <div class="p-cont">
        <div class="title ep-bg-purple">
          <span>付款信息</span>
        </div>
        <div class="detail">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="d-label">付款项目：</div>
              <div class="d-value">
                {{
                  (orderData.paymentInfo.paymentClass &&
                    paymentClassMap[orderData.paymentInfo.paymentClass]) ||
                  "-"
                }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">付款方式：</div>
              <div class="d-value">
                {{
                  orderData.paymentInfo.isDiseaseCard === 0
                    ? `${orderData.paymentInfo.paymentType}（门慢）`
                    : orderData.paymentInfo.paymentType || "-"
                }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">付款金额：</div>
              <div class="d-value">
                {{ formatMoney(orderData.paymentInfo[0].amount, 2) || "-" }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">付款时间：</div>
              <div class="d-value">
                {{
                  orderData.paymentInfo.createDate === "-"
                    ? "-"
                    : moment(orderData.paymentInfo.createDate).format(
                        "YYYY-MM-DD HH:mm:ss"
                      )
                }}
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <div class="part">
      <div class="p-cont">
        <div class="title ep-bg-purple">
          <span>收件人信息</span>
        </div>
        <div class="detail">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="d-label">收件人：</div>
              <div class="d-value">
                {{ orderData.deliveryRecipientName }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">联系方式：</div>
              <div class="d-value">
                {{ orderData.deliveryRecipientContact }}
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="p-cont">
        <div class="title ep-bg-purple">
          <span>配送信息</span>
        </div>
        <div class="detail">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="d-label">配送方式：</div>
              <div class="d-value">
                {{ deliveryAddressType }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">收件地址：</div>
              <div class="d-value">
                {{
                  orderData.deliveryAddress || orderData.shippingAddress.address
                }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">自提点：</div>
              <div class="d-value">
                {{ selfPickupAddress }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">承运商：</div>
              <div class="d-value">
                {{
                  (orderData.logisticsInformation &&
                    orderData.logisticsInformation.expressCompany) ||
                  "-"
                }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">运单编号：</div>
              <div class="d-value">
                {{
                  (orderData.logisticsInformation &&
                    orderData.logisticsInformation.expressNumber) ||
                  "-"
                }}
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="p-cont">
        <div class="title ep-bg-purple">
          <span>系统信息</span>
        </div>
        <div class="detail">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="d-label">创建人：</div>
              <div class="d-value">
                {{ orderData.createBy.createByName }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">创建机构：</div>
              <div class="d-value">
                {{ orderData.createBy.createCompany }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">创建时间：</div>
              <div class="d-value">
                {{ orderData.createBy.createDate }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">创建系统：</div>
              <div class="d-value">
                {{ channel(orderData.createBy.channel) }}
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="d-label">开具医生：</div>
              <div class="d-value">
                {{ orderData.orderHospital.orderDoctorName }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">开具医院：</div>
              <div class="d-value">
                {{ orderData.orderHospital.orderHospitalName }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">开具时间：</div>
              <div class="d-value">
                {{
                  orderData.orderHospital.orderDate &&
                  moment(orderData.orderHospital.orderDate).format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">开具系统：</div>
              <div class="d-value">
                {{ channel(orderData.orderHospital.channel) }}
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="d-label">审核药师：</div>
              <div class="d-value">
                {{ orderData.pharmacistAudited.pharmacistAuditedName }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">审核机构：</div>
              <div class="d-value">
                {{ orderData.pharmacistAudited.pharmacistAuditedCompany }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">审核日期：</div>
              <div class="d-value">
                {{
                  orderData.pharmacistAudited.pharmacistAuditedDate &&
                  moment(
                    orderData.pharmacistAudited.pharmacistAuditedDate
                  ).format("YYYY-MM-DD HH:mm:ss")
                }}
              </div>
            </el-col>
            <el-col :span="6">
              <div class="d-label">审核系统：</div>
              <div class="d-value">
                {{ orderData.pharmacistAudited.pharmacistSystem }}
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import moment from "moment";
const router = useRouter();
// 获取接口返回的数据
const orderDetail = localStorage.getItem("orderDetail");
const orderData = ref<any>({
  id: "",
  orderNo: "",
  cycle: 0, //用药周期
  status: "10", //订单状态,
  deliveryAddress: "",
  deliveryAddressType: 1, //配送方式 1=居住地址 2=社区医院 3=自定义（1、3为配送，2为自提）
  deliveryReceipientName: "",
  deliveryReceipientContact: "",
  deliveryTime: "", //配送时间
  deliveryProvinceId: "",
  deliveryCityId: "",
  deliveryAreaId: "",
  prescriptionStatus: 10, //处方状态
  orderPictureUrl: "", //订单图片
  isPay: 1, //是否支付 0=待支付 1=已支付
  pictures: ["/orderinfo/20190627/9a3fc199d60748bea3eed8ac851b5cd8.jpg"],
  sources: 1, //来源渠道
  realAmount: 1200, //实售金额，以分为单位的整数
  patient: {
    //客户信息取自订单表
    id: "15574e24f0394a40a94eb2383e353560", //客户id
    patientName: "客户姓名",
    patientSex: 0, //客户性别 0=女 1=男
    patientAge: 59, //客户年龄
    allergies: "过敏史"
  },
  orderHospital: {
    //开具机构
    orderHospitalName: "开具机构",
    orderDoctorName: "开具医生",
    orderDate: "2017-01-01 00:00:00", //开具时间
    channel: 1 //开具系统 1=医生端 2=指挥中心 3=呼叫中心
  },
  shippingAddress: {
    //取药点
    shippingAddressId: "取药点id",
    shippingAddressName: "取药点名称",
    packageReceiver: "取药点联系人",
    packageReceiverPhone: "取药点联系电话",
    address: "取货地址" //省市区街道
  },
  diseases: [
    //疾病诊断
    {
      id: "疾病id",
      name: "疾病名称"
    }
  ],
  drugs: [
    //药品信息
    {
      id: "药品id",
      commonName: "通用名",
      producerName: "生产厂家",
      productCode: "产品编码",
      productName: "商品名",
      amount: 2, //数量,
      useAmount: 5, //单次用量
      frequency: 1, //频次 1=qd 每日一次 2=bid 每日两次 3=tid 每日三次 4=qid 每日四次 5=qn 每夜一次 6=qw 每周一次
      preparationUnit: "20mg", //剂量
      packageSize: "48", //包装规格量
      minimumUnit: "片", //最小使用单位
      packageUnit: "盒", //包装单位
      priceCent: 1200, //单价，以分为单位的整数
      whScale: 20, //报销比例 以百分之一为单位的整数
      realQuantity: 2, //实际销售数量 0用-表示。需要从包裹药品表中获取
      realWhScale: 20, //实际报销比例 以百分之一为单位的整数
      realIntegralScale: 20, //实际报销积分比例 以百分之一为单位的整数
      drugType: 1 //药品分类 1=处方药 2=非处方药 3=中药饮品
    }
  ],
  createBy: {
    //创建人
    createById: "创建人id",
    createByName: "创建人姓名",
    createDate: "2017-01-01 00:00:00", //创建时间
    createCompany: "创建机构", //创建机构名称
    channel: 1 //开具系统 1=医生端 2=指挥中心 3=呼叫中心
  },
  pharmacistAudited: {
    //审核药师
    pharmacistAuditedId: "药师审核人id",
    pharmacistAuditedName: "药师审核人姓名",
    pharmacistAuditedDate: "2017-01-01 00:00:00", //药师审核时间
    pharmacistAuditedCompany: "审核机构", //审核机构名称
    pharmacistSystem: "药师系统",
    pharmacistRejected: "审核不通过原因",
    pharmacistUpdate: 1 //是否需要补充资料 0=否 1=是
  },
  paymentInfo: [
    //付款信息
    {
      paymentType: "付款方式", //直接返回中文
      isDiseaseCard: 0, //是否门慢 0=是，1=否  注意！！！
      amount: 1000, //付款金额，以分为单位的整数
      createDate: "2017-01-01 00:00:00", //付款时间
      largeClass: 2, //支付大类 2万户自收
      groupId: 27, //支付中类 27商保
      paytypeId: 1 //支付小类 1保险直赔
    }
  ],
  orderFlow: [
    //订单流水
    {
      createDate: "2017-01-01 00:00:00", //创建时间
      userName: "操作人",
      status: 10, //订单状态
      content: "订单流水内容"
    }
  ],
  logisticsInformation: {
    //物流信息
    expressCompany: "快递公司",
    expressNumber: "快递单号"
  },
  refundMoney: "1.23", //返现金xx
  refundPoints: 123 //返积分
});
console.log("orderData:", orderData.value);
if (orderDetail && orderDetail !== "undefined" && orderDetail !== "null") {
  try {
    orderData.value = JSON.parse(orderDetail);
  } catch (error) {
    ElMessage({
      type: "error",
      message: "详情内容不存在，请重新查找"
    });
    router.push("/supply/order");
  }
} else {
  ElMessage({
    type: "error",
    message: "详情内容不存在，请重新查找"
  });
  router.push("/supply/order");
}

const MAX_SAFE_INTEGER = 9007199254740991;
const MIN_SAFE_INTEGER = -9007199254740991;

const moneyCent = ref(0);
const whMoneyCentPercent = ref(0);
const realyMoneyCent = ref(orderData.value.realAmount);
const realyWhMoneyCentPercent = ref(0);

// 计算各种金额
orderData.value.drugs.forEach(item => {
  moneyCent.value += item.priceCent * item.amount;
  whMoneyCentPercent.value += item.priceCent * item.amount * item.whScale;

  realyWhMoneyCentPercent.value +=
    item.priceCent * item.realQuantity * item.realWhScale;
});

const whMoneyCent = ref(
  isInteger(whMoneyCentPercent.value)
    ? refundRountCentPercentToCent(whMoneyCentPercent.value)
    : NaN
);

const refundCont = ref(formatMoney(whMoneyCent.value, 1));

const deliveryAddressType = ref("");
if (orderData.value.deliveryAddressType) {
  if (
    orderData.value.deliveryAddressType === 1 ||
    orderData.value.deliveryAddressType === 3
  ) {
    deliveryAddressType.value = "配送";
  } else {
    deliveryAddressType.value = "自提";
  }
} else {
  deliveryAddressType.value = "-";
}

const selfPickupAddress = ref(
  deliveryAddressType.value === "自提"
    ? (orderData.value &&
        orderData.value.shippingAddress &&
        orderData.value.shippingAddress.shippingAddressName) ||
        "-"
    : "-"
);

// console.log("orderData:", orderData);

const StatusChoices = [
  { value: "10", label: "初始订单" },
  { value: "20", label: "患者已确认" },
  { value: "30", label: "医生已确认" },
  { value: "35", label: "药师已确认" },
  { value: "40", label: "备药中" },
  { value: "45", label: "配送中" },
  { value: "50", label: "待取药" },
  // { value: '60', label: '已取药' },
  // { value: '70', label: '正在使用' },
  { value: "97", label: "已驳回" },
  { value: "98", label: "撤单" },
  { value: "99", label: "完成" }
];
const StatusMap = {};

StatusChoices.forEach(item => (StatusMap[item.value] = item.label));

const isPayStatusChoices = [
  { value: "1", label: "已支付" },
  { value: "0", label: "未支付" }
];

const isPayStatusMap = {};
isPayStatusChoices.forEach(item => (isPayStatusMap[item.value] = item.label));

const prescriptionStatusChoices = [
  { value: "10", label: "无处方" },
  { value: "20", label: "待接诊" },
  { value: "30", label: "开具中" },
  { value: "40", label: "申请失败" },
  { value: "50", label: "被拒开" },
  { value: "60", label: "有处方" }
];

const prescriptionStatusMap = {};
prescriptionStatusChoices.forEach(
  item => (prescriptionStatusMap[item.value] = item.label)
);

const paymentClassMap = reactive({
  1: "药品费用",
  2: "运费",
  default: "-"
});

function formatterDrugType(row) {
  const drugTypeObj = {
    1: "处方药",
    2: "非处方药",
    3: "中药饮品"
  };
  return drugTypeObj[row.drugType];
}

function formatterFrequency(row) {
  const feqObj = {
    1: "qd 每日一次",
    2: "bid 每日两次",
    3: "tid 每日三次",
    4: "qid 每日四次",
    5: "qn 每夜一次",
    6: "qw 每周一次"
  };
  return feqObj[row.frequency];
}
function isInteger(num) {
  if (typeof num !== "number" || isNaN(num) || !isFinite(num)) {
    return false;
  }
  return num < MAX_SAFE_INTEGER && num > MIN_SAFE_INTEGER && !(num % 1);
}

function count(n, digits) {
  if (digits === 2) {
    const remainder = n % 100;
    if (remainder >= 10) {
      return `${(n / 100) << 0}.${remainder}`;
    }
    return `${(n / 100) << 0}.0${remainder}`;
  } else if (digits === 1) {
    if (n % 10 !== 0) {
      throw new Error(
        `centToYuan Convert ${n} cents to 1 digits yuan will lose precision`
      );
    }
    const m = (n / 10) << 0;
    return `${(m / 10) << 0}.${m % 10}`;
  } else if (digits === 0) {
    console.log("count n:", n);
    if (n % 100 !== 0) {
      throw new Error(
        `centToYuan Convert ${n} cents to 0 digits yuan will lose precision`
      );
    }
    return `${(n / 100) << 0}`;
  }
  throw new Error("centToYuan only accept 0, 1, 2 digits");
}
function centToYuan(n, digits) {
  if (!isInteger(n)) {
    throw new Error(`centToYuan only accept integers as input`);
  }
  if (n < 0) {
    return `-${count(Math.abs(n), digits)}`;
  } else {
    return count(n, digits);
  }
}
function formatMoney(num, digits) {
  console.log("num:", num);
  console.log("digits:", digits);
  return `¥${centToYuan(num, digits || 2)}`;
}

function replaceRealNum(data, text) {
  if (data === 0 || isNaN(data)) {
    return "-";
  } else {
    if (text) return `${data}${text}`;
    return `${data}`;
  }
}

function refundRountCentPercentToCent(centPercent) {
  if (!isInteger(centPercent)) {
    throw new Error(
      "roundRefundCentPercentToCent only accept integers as input"
    );
  }
  let n = centPercent;
  if (n % 1000 !== 0) {
    n = n - (n % 1000) + 1000;
  }
  return (n / 100) << 0;
}

function replaceZero(data, text) {
  if (data === 0 || isNaN(data)) {
    return "-";
  } else {
    return text;
  }
}

function channel(channel) {
  switch (channel) {
    case 1:
      return "医生端";
    case 2:
      return "指挥中心";
    case 3:
      return "呼叫中心";
    case 4:
      return "药店端预定";
    case 5:
      return "药店端现场购药";
    case 6:
      return "万户健康微信号";
    case 7:
      return "第三方";
    case 8:
      return "万户微孝";
    case 9:
      return "主动配送";
    case 10:
      return "健康卡服务";
    case 11:
      return "平安慢病卡";
    case 12:
      return "七鱼客服";
    case 13:
      return "PBM APP";
    case 14:
      return "到店购买";
    case 15:
      return "公益项目";
    default:
      return channel;
  }
}
</script>
<style scoped lang="scss">
.main {
  .part {
    padding: 0px;
  }

  .p-title {
    padding: 10px 20px;
  }

  .p-cont {
    padding-bottom: 20px;
    margin-top: 0px;

    .title {
      font-weight: bold;
      font-size: 18px;
      padding: 20px 20px 0px 20px;
    }
  }

  .detail {
    padding: 0px 20px;
    margin-top: 20px;

    .el-row {
      padding: 10px 0px;
    }

    .el-col {
      display: flex;
      align-items: center;
      margin-top: 10px;

      .d-label {
      }

      .d-value {
        width: 70%;
        border-bottom: 1px solid rgb(224, 224, 226);
      }
    }

    .table-footer {
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      color: black;

      .el-row {
        width: 600px;
        padding: 0px;
      }
    }
  }
}
</style>
